package com.qeegoo.b2bautozityp.moudle.login.viewmodel;

import android.databinding.ObservableField;

import com.bigkoo.pickerview.OptionsPickerView;
import com.kelin.mvvmlight.command.ReplyCommand;
import com.orhanobut.logger.Logger;
import com.qeegoo.b2bautozityp.api.HttpParams;
import com.qeegoo.b2bautozityp.api.ProgressSubscriber;
import com.qeegoo.b2bautozityp.api.RequestApi;
import com.qeegoo.b2bautozityp.api.RetrofitService;
import com.qeegoo.b2bautozityp.api.entity.HttpResult;
import com.qeegoo.b2bautozityp.moudle.login.model.ProvinceBean;
import com.qeegoo.b2bautozityp.moudle.login.view.RegisterSuccessActivity;
import com.qeegoo.b2bautozityp.utils.JsonUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import base.lib.util.ActivityManager;
import base.lib.util.NavigateUtils;
import base.lib.util.ToastUtils;

/**
 * Created by lining on 2017/9/19.
 */

public class RegisterViewModel {
    private final static String fileName = "data.json";
    public final static String kResponse_province = "province";
    public final static String kResponse_areaId = "id";
    public final static String kResponse_city = "city";
    public final static String kResponse_district = "district";
    public static final String kResponse_areaName = "name";

    private JSONObject orginData;
    private String stringAreaID = "";
    private ArrayList<ProvinceBean> options1Items = new ArrayList<ProvinceBean>();
    private ArrayList<ArrayList<ProvinceBean>> options2Items = new ArrayList<ArrayList<ProvinceBean>>();
    private ArrayList<ArrayList<ArrayList<ProvinceBean>>> options3Items = new ArrayList<ArrayList<ArrayList<ProvinceBean>>>();

    private RequestApi mRequestApi;
    public ObservableField<String> name = new ObservableField<>("");
    public ObservableField<String> loginName = new ObservableField<>("");
    public ObservableField<String> mobile = new ObservableField<>("");
    public ObservableField<String> sAreaName = new ObservableField<>("");
    public ObservableField<String> address = new ObservableField<>("");
    public ObservableField<String> email = new ObservableField<>("");
    public ObservableField<String> connector = new ObservableField<>("");
    public ObservableField<String> password = new ObservableField<>("");
    public ObservableField<String> confirmPassword = new ObservableField<>("");
    public ObservableField<Boolean> checked = new ObservableField<>(false);
    public ObservableField<Boolean> isloaded = new ObservableField<>(false);
    public OptionsPickerView pvOptions ;

    public RegisterViewModel(RequestApi requestApi) {
        mRequestApi = requestApi;
        pvOptions = new OptionsPickerView(ActivityManager.getActivity());
        try {
            getAllAreas();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //加盟入驻
    public ReplyCommand conformCommand = new ReplyCommand(() -> {
        mRequestApi.register(HttpParams.register(name.get(),loginName.get(),mobile.get(),stringAreaID
                ,connector.get(),email.get(),address.get(),password.get(),confirmPassword.get()))
                .compose(RetrofitService.applySchedulers())
                .subscribe(new ProgressSubscriber<HttpResult>() {
                    @Override
                    public void onNext(HttpResult httpResult) {
                        if (httpResult.getStatus().isSuccess()){
                            NavigateUtils.startActivity(RegisterSuccessActivity.class);
                            ActivityManager.getActivity().finish();
                        }else {
                            ToastUtils.showToast(httpResult.getStatus().getMsg());
                        }
                    }
                });
    });

    //选择区域
    public ReplyCommand sAreaCommand = new ReplyCommand(() -> {
//        ToastUtils.showToast("选择区域");

        if (!isloaded.get()){
            pvOptions.setPicker(options1Items, options2Items, options3Items, true);
            //设置选择的三级单位
            pvOptions.setTitle("选择所属区域");
            pvOptions.setCyclic(false, false, false);
            //设置默认选中的三级项目
            //监听确定选择按钮
            pvOptions.setSelectOptions(0, 0, 0);
            pvOptions.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {

                @Override
                public void onOptionsSelect(int options1, int option2, int options3) {
                    //返回的分别是三个级别的选中位置
                    String tx = "";
                    stringAreaID = "";
                    if (options1Items.size() == 0 || options1Items.get(options1) == null) return;
                    tx += options1Items.get(options1).getPickerViewText();
                    stringAreaID = options1Items.get(options1).getId();
                    sAreaName.set(tx);
                    Logger.e("=====所选区域id=====" + stringAreaID);
                    if (options2Items.get(options1).size() == 0 || options2Items.get(options1).get(option2) == null)
                        return;
                    tx += options2Items.get(options1).get(option2).getPickerViewText();
                    stringAreaID = options2Items.get(options1).get(option2).getId();
                    sAreaName.set(tx);
                    Logger.e("=====所选区域id=====" + stringAreaID);
                    if (options3Items.get(options1).get(option2).size() == 0 || options3Items.get(options1).get(option2).get(options3) == null)
                        return;
                    tx += options3Items.get(options1).get(option2).get(options3).getPickerViewText();
                    stringAreaID = options3Items.get(options1).get(option2).get(options3).getId();
                    sAreaName.set(tx);
                    Logger.e("=====所选区域id=====" + stringAreaID);
                }
            });
            isloaded.set(true);
            pvOptions.show();
        } else {
            pvOptions.show();
        }
    });

    //我已阅读并同意
    public ReplyCommand checkCommand = new ReplyCommand(() -> {
        if (checked.get()){
            checked.set(false);
        }else {
            checked.set(true);
        }
    });

    //《供应商服务协议》
    public ReplyCommand licenceCommand = new ReplyCommand(() -> {
        ToastUtils.showToast("《供应商服务协议》");
    });

    public void getAllAreas() throws JSONException {
        String jsonStr= "";
        jsonStr= JsonUtils.getJson(ActivityManager.getActivity(),fileName);
//        String jsonStr= JsonUtils.getJson(ActivityManager.getActivity(),fileName);
        Logger.e("选择区域:"+jsonStr,"");
        orginData = new JSONObject(jsonStr);
        JSONObject objectCity= orginData.optJSONObject(kResponse_city);
        JSONObject objectDistrict= orginData.optJSONObject(kResponse_district);
        JSONArray provinces = orginData.getJSONArray(kResponse_province);
            ArrayList<ProvinceBean> options2Items_city ;
            ArrayList<ArrayList<ProvinceBean>> options3Items_district ;
            for (int i = 0; i < provinces.length(); i++) {
                options3Items_district = new ArrayList<ArrayList<ProvinceBean>>();
                options2Items_city = new ArrayList<ProvinceBean>();
                JSONObject proviceObj = null;
                try {
                    proviceObj = provinces.getJSONObject(i);
                    ProvinceBean provinceBean = new ProvinceBean(proviceObj.optString(kResponse_areaId), proviceObj.optString(kResponse_areaName));
                    JSONArray citys = objectCity.getJSONArray(proviceObj.optString(kResponse_areaId));
                    if (citys.length() == 0) continue;
                    for (int j = 0; j < citys.length(); j++) {
                        ArrayList<ProvinceBean> item3 = new ArrayList<ProvinceBean>();
                        JSONObject cityObj = citys.getJSONObject(j);
                        ProvinceBean cityBean = new ProvinceBean(cityObj.optString(kResponse_areaId), cityObj.optString(kResponse_areaName));
                        JSONArray districts = objectDistrict.optJSONArray(cityObj.optString(kResponse_areaId));
                        if (districts == null) break;
                        for (int k = 0; k < districts.length(); k++) {
                            JSONObject districtObj = districts.getJSONObject(k);
                            ProvinceBean districtBean = new ProvinceBean(districtObj.optString(kResponse_areaId), districtObj.optString(kResponse_areaName));
                            item3.add(districtBean);
                        }
                        options2Items_city.add(cityBean);
                        options3Items_district.add(item3);
                    }
                    options1Items.add(provinceBean);
                    options2Items.add(options2Items_city);
                    options3Items.add(options3Items_district);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

    }
}
